import React, { useState, useEffect } from 'react'
import { Card, Select, Space, Spin, Alert, Button } from 'antd'
import { Line } from '@ant-design/charts'
import { ReloadOutlined } from '@ant-design/icons'
import { apiService, RateResponse } from '../services/api'
import dayjs from 'dayjs'

const { Option } = Select

const RatesChart: React.FC = () => {
  const [cnyData, setCnyData] = useState<RateResponse[]>([])
  const [usdData, setUsdData] = useState<RateResponse[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [interval, setInterval] = useState<'30m' | '1d'>('1d')

  const fetchData = async () => {
    try {
      setLoading(true)
      setError(null)
      
      const endDate = dayjs().format('YYYY-MM-DD')
      const startDate = dayjs().subtract(30, 'day').format('YYYY-MM-DD')
      
      const [cnyResult, usdResult] = await Promise.all([
        apiService.getRates('CNY', startDate, endDate, interval),
        apiService.getRates('USD', startDate, endDate, interval)
      ])
      
      setCnyData(cnyResult)
      setUsdData(usdResult)
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchData()
  }, [interval])

  const handleRefresh = () => {
    fetchData()
  }

  // 准备图表数据
  const chartData = [
    ...cnyData.map(item => ({
      date: dayjs(item.ts_utc).format('MM-DD'),
      time: item.ts_utc,
      value: item.rate,
      amount: item.amount_1000,
      type: 'JPY→CNY',
      currency: 'CNY'
    })),
    ...usdData.map(item => ({
      date: dayjs(item.ts_utc).format('MM-DD'),
      time: item.ts_utc,
      value: item.rate,
      amount: item.amount_1000,
      type: 'JPY→USD',
      currency: 'USD'
    }))
  ]

  const config = {
    data: chartData,
    xField: 'time',
    yField: 'value',
    seriesField: 'type',
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
    tooltip: {
      formatter: (datum: any) => {
        return {
          name: datum.type,
          value: `${datum.value.toFixed(6)} (1000JPY = ${datum.amount.toFixed(2)}${datum.currency})`
        }
      }
    },
    legend: {
      position: 'top' as const,
    },
    color: ['#1890ff', '#52c41a'],
    point: {
      size: 3,
      shape: 'circle',
    },
    line: {
      size: 2,
    },
  }

  if (loading && chartData.length === 0) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
        <div style={{ marginTop: 16 }}>加载图表数据中...</div>
      </div>
    )
  }

  if (error) {
    return (
      <Alert
        message="图表数据加载失败"
        description={error}
        type="error"
        action={
          <Button size="small" onClick={handleRefresh}>
            重试
          </Button>
        }
        showIcon
      />
    )
  }

  return (
    <Card 
      title="汇率趋势图（近30天）"
      extra={
        <Space>
          <Select 
            value={interval} 
            onChange={setInterval}
            style={{ width: 100 }}
          >
            <Option value="1d">日线</Option>
            <Option value="30m">30分钟</Option>
          </Select>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            loading={loading}
          >
            刷新
          </Button>
        </Space>
      }
      className="chart-container"
    >
      {chartData.length > 0 ? (
        <Line {...config} />
      ) : (
        <Alert message="暂无图表数据" type="warning" showIcon />
      )}
    </Card>
  )
}

export default RatesChart
